package ee.logsimulator.ui;

import ee.logsimulator.parser.data.Raid;
import ee.logsimulator.parser.data.Zone;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Graphics;

import javax.swing.JComponent;
import javax.swing.JToolTip;
import javax.swing.plaf.basic.BasicToolTipUI;

public class RaidToolTipUI extends BasicToolTipUI {
  private static final long serialVersionUID = 1L;
  private Raid raid;

  @Override
  public void paint(Graphics g, JComponent c) {
    g.setColor(Color.BLACK);
    g.fillRect(0, 0, c.getWidth(), c.getHeight());
    g.setColor(Color.WHITE);
    g.drawRect(0, 0, c.getWidth() - 1, c.getHeight() - 1);

    int drawnTo = 0;

    for (Zone zone : raid.report.zones) {
      g.setColor(Color.WHITE);
      FontMetrics metrics = g.getFontMetrics();
      drawnTo = drawnTo + metrics.getHeight();
      g.drawString(zone.name, 5, drawnTo);
      if (zone.bosses != null) {
        for (Object[] o : zone.bosses) {
          drawnTo = drawnTo + metrics.getHeight();
          g.setColor((Boolean) o[1] ? Color.GREEN : Color.RED);
          g.drawString(getBossName(o), 20, drawnTo);
        }
      }
    }
  }

  public static String getBossName(Object[] o) {
    String name = o[0].toString();
    int tries = (Integer) o[2];
    if (tries > 0) {
      name += " (" + tries + ")";
    }
    return name;
  }

  public RaidToolTipUI(Raid raid) {
    this.raid = raid;
  }

  public static class RaidToolTip extends JToolTip {
    private static final long serialVersionUID = 1L;
    private Raid raid;

    public RaidToolTip(Raid raid) {
      this.raid = raid;
      setUI(new RaidToolTipUI(raid));
    }

    @Override
    public Dimension getPreferredSize() {
      Graphics g = getComponent().getGraphics();
      FontMetrics metrics = g.getFontMetrics();
      int drawnToX = 5;
      int drawnToY = 0;
      for (Zone zone : raid.report.zones) {
        drawnToY = drawnToY + metrics.getHeight();
        drawnToX = Math.max(drawnToX, 5 + metrics.stringWidth(zone.name));
        if (zone.bosses != null) {
          for (Object[] o : zone.bosses) {
            drawnToY = drawnToY + metrics.getHeight();
            drawnToX = Math.max(drawnToX, 20 + metrics.stringWidth(RaidToolTipUI.getBossName(o)));
          }
        }
      }
      return new Dimension(drawnToX + 5, drawnToY + 5);
    }
  }

}
